//
//  ViewController.swift
//  DiceGame
//
//  Created by tanwz on 16/11/17.
//  Copyright © 2016年 tanwz. All rights reserved.
//

import UIKit

class ViewController: UIViewController, GameDelegate, CAAnimationDelegate {
    
    @IBOutlet weak var playBtn: UIButton!
    @IBOutlet weak var rollBtn: UIButton!
    @IBOutlet weak var scoreLb: UILabel!
    @IBOutlet weak var boardView: BoardView!
    var gameControl: GameControl? = nil
    
    private var sprite: UIImageView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        sprite = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        sprite?.backgroundColor = UIColor.blue
        sprite?.isHidden = true
        view.addSubview(sprite!)
        
        gameControl = GameControl()
        gameControl?.delegate = self
        updateBtns()
        updateStep()
        
        if let boards = gameControl?.boards {
            for i in 0..<boards.count {
                if boards[i] > 0 {
                    if boardView.ladders == nil {
                        boardView.ladders = [(Int, Int)]()
                    }
                    boardView.ladders?.append((i, i + boards[i]))
                } else if boards[i] < 0 {
                    if boardView.snakes == nil {
                        boardView.snakes = [(Int, Int)]()
                    }
                    boardView.snakes?.append((i, i + boards[i]))
                }
            }
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func onRoll(_ sender: Any) {
        gameControl?.roll()
    }
    
    @IBAction func onPlay(_ sender: Any) {
        gameControl?.startGame()
    }
    
    //MARK: - game delegate
    func didRoll(side: Int) {
        print(#file.components(separatedBy: "/").last!  + "::" + #function + "\(side)")
        updateStep()
    }
    
    func willMove(from: Int, to: Int, isLinear: Bool) {
        //path
        //animating
        print("willmove from:\(from) to:\(to) linear:\(isLinear)")
        
        let movePath = createPath(from: from, to: to, linear: isLinear)
        
        let animation = CAKeyframeAnimation(keyPath: "position")
        animation.path = movePath.cgPath
        animation.duration = 1.3
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
        animation.autoreverses = false
        animation.fillMode = kCAFillModeForwards
        animation.isRemovedOnCompletion = false
        animation.delegate = self
        self.sprite?.layer.add(animation, forKey: "fff")
    }
    
    func gameStart() {
        print(#file.components(separatedBy: "/").last!  + "::" + #function)
        
        updateBtns()
        updateStep()
        
        sprite?.layer.removeAnimation(forKey: "fff")
        sprite?.isHidden = false
        sprite?.center = boardCenter(at: 0)
    }
    
    func gameOver() {
        print(#file.components(separatedBy: "/").last!  + "::" + #function)
        updateBtns()
    }
    
    func updateStep() {
        scoreLb.text = "\(gameControl!.totalStep)"
    }
    
    func updateBtns() {
        self.playBtn.isEnabled = !(gameControl!.started)
        self.rollBtn.isEnabled = gameControl!.started
    }
    
    private func boardCenter(at index: Int) -> CGPoint {
        var index = index
        if index >= (gameControl?.boardCount)! {
            index = (gameControl?.boardCount)! - 1
        }
        let rect = view.convert(boardView!.boards![index], from: boardView)
        return CGPoint(x: rect.midX, y: rect.midY)
    }
    
    private func createPath(from: Int, to: Int, linear:Bool) -> UIBezierPath {
        let path = UIBezierPath()
        path.move(to: boardCenter(at: from))
        
        if linear {
            path.addLine(to: boardCenter(at: to))
        } else {
            for i in from ... to {
                path.addLine(to: boardCenter(at: i))
            }
        }
        
        return path
    }
    
    //MARK: - animation delegate
    func animationDidStart(_ anim: CAAnimation) {
        print(#file.components(separatedBy: "/").last!  + "::" + #function)
        rollBtn.isEnabled = false;
    }
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        print(#file.components(separatedBy: "/").last!  + "::" + #function)
        rollBtn.isEnabled = true
        gameControl?.commit()
    }
}

